package com.sunnada.edu.business.attendance.service;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.sunnada.edu.business.attendance.dao.AttendanceDao;
import com.sunnada.edu.system.pub.util.Utils;

@Service
@Transactional
public class AttendanceServiceImpl implements AttendanceService {
	private static final Logger logger = LoggerFactory.getLogger(AttendanceServiceImpl.class);
	@Resource
	AttendanceDao attendanceDao;

	@Override
	public int getAttendanceCots(HashMap<String, String> params) {
		return attendanceDao.getAttendanceCots(params);
	}

	@Override
	public List<?> findAttendance(HashMap<String, String> params) {
		return attendanceDao.findAttendance(params);
	}

	@Override
	public String attendanceDelete(HashMap<String, String> params) {
		String msg = "";
		int num = attendanceDao.attendanceDelete(params);
		attenworkerDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String attendanceAdd(HashMap<String, String> params) {
		String msg = "";
			int num = attendanceDao.attendanceAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
				String pNumber = params.get("pNumber");
				if( !pNumber.equals("0") ){
					String wkId = params.get("wkIds");
					String[] wkIds = wkId.split(",");
					for (int i = 0; i < wkIds.length; i++) {
						HashMap<String, String> param = new HashMap<String, String>();
						param.put("recId", params.get("recId"));
						param.put("jobId",wkIds[i]);
						param.put("begTime", params.get("begTime"));
						param.put("endTime", params.get("endTime"));
						param.put("signTime", params.get("signTime"));
						param.put("signoutTime", params.get("signoutTime"));
						param.put("signTime2", params.get("signTime2"));
						param.put("signoutTime2", params.get("signoutTime2"));
					    attendanceDao.attenworkerAdd(param);
					}
				}
				
			}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String attendanceUpdate(HashMap<String, String> params) {
		String msg = "";
			int num = attendanceDao.attendanceUpdate(params);
			params.put("recIds", Utils.getSqlSplitStr(params.get("recId")));
			attenworkerDelete(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
				String wkId = params.get("wkIds");
				if(Utils.isNotNull(wkId)){
					String[] wkIds = wkId.split(",");
					for (int i = 0; i < wkIds.length; i++) {
						HashMap<String, String> param = new HashMap<String, String>();
						param.put("recId", params.get("recId"));
						param.put("jobId",wkIds[i]);
						param.put("begTime", params.get("begTime"));
						param.put("endTime", params.get("endTime"));
						param.put("signTime", params.get("signTime"));
						param.put("signoutTime", params.get("signoutTime"));
						param.put("signTime2", params.get("signTime2"));
						param.put("signoutTime2", params.get("signoutTime2"));
					    attendanceDao.attenworkerAdd(param);
					}
				}
			}
		return msg;
	}

	@Override
	public Map attendanceByRecId(HashMap<String, String> params) {
		return attendanceDao.attendanceByRecId(params);
	}

	@Override
	public int getWorkerCots(HashMap<String, String> params) {
		return attendanceDao.getWorkerCots(params);
	}

	@Override
	public List<?> findWorkers(HashMap<String, String> params) {
		return attendanceDao.findWorkers(params);
	}
	
	@Override
	public String attenworkerAdd(HashMap<String, String> params) {
		String msg = "";
			int num = attendanceDao.attenworkerAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}

		return msg;
	}
	
	@Override
	public String findAttenworker(HashMap<String, String> params) {
		List<?> l = attendanceDao.findAttenworker(params);
		String wokIds = "";
		String sgTime = params.get("signTime");
		String soTime = params.get("signoutTime");
		String jobnos = params.get("jobnos");
		for (int i = 0; i < l.size(); i++) {
			HashMap<String, String> param = new HashMap<String, String>();
			param = (HashMap<String, String>) l.get(i);
			String bgtime = param.get("SIGN_TIME");
			String egtime = param.get("SIGNOUT_TIME");
			if(Utils.isNotNull(param.get("SIGNOUT_TIME2"))){
				egtime = param.get("SIGNOUT_TIME2");
			}
			boolean isexist = false;
			DateFormat df = new SimpleDateFormat("HH:mm:ss");
			try
			{
			    Date sg = df.parse(sgTime);
			    Date so = df.parse(soTime);
			    Date bg = df.parse(bgtime);
			    Date eg = df.parse(egtime);
			    
			    if((bg.getTime() - sg.getTime())>=0 && (eg.getTime() - so.getTime())>=0 && (so.getTime() - bg.getTime())>=0 ){
			    	isexist = true;
			    }
			    if((sg.getTime() - bg.getTime())>=0 && (eg.getTime() - so.getTime())>=0){
			    	isexist = true;
			    }
			    if((sg.getTime() - bg.getTime())>=0 && (so.getTime() - eg.getTime())>=0 && (eg.getTime() - sg.getTime())>=0 ){
			    	isexist = true;
			    }
			    if((bg.getTime() - sg.getTime())>=0 && (so.getTime() - eg.getTime())>=0 ){
			    	isexist = true;
			    }
			    if(isexist == true ){
			    	boolean isSave = false;
			    	 if(Utils.isNotNull(jobnos)){
			    		String[] jo =  jobnos.split(",");
			    		for (int j = 0; j < jo.length; j++) {
							if(param.get("JOBNO").equals(jo[j])){
								isSave = true;
							}
						}
			    	 }
			    	 if(isSave == false){
			    		 wokIds += param.get("JOBNO")+","; 
			    	 }
			    }
			}
			catch (Exception e)
			{}
			
		}
		if(wokIds.endsWith(",")){
			wokIds = wokIds.substring(0,wokIds.length()-1);
		}
		return wokIds;
	}
	
	@Override
	public String attenworkerById(HashMap<String, String> params) {
		List<?> l = attendanceDao.attenworkerById(params);
		String jobnos = "";
		for (int i = 0; i < l.size(); i++) {
			HashMap<String, String> param = (HashMap<String, String>) l.get(i);
			jobnos += param.get("JOBNO")+",";
		}
		if(jobnos.endsWith(",")){
			jobnos = jobnos.substring(0,jobnos.length()-1);
		}
		return jobnos;
	}
	
	@Override
	public String attenworkerDelete(HashMap<String, String> params) {
		String msg = "";
		int num = attendanceDao.attenworkerDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}
	
	@Override
	public String getWorkers(HashMap<String, String> params) {
		List<?> l = attendanceDao.getWorkers(params);
		String jobnos = "";
		for (int i = 0; i < l.size(); i++) {
			HashMap<String, String> param = (HashMap<String, String>) l.get(i);
			jobnos += param.get("JOBNO")+",";
		}
		if(jobnos.endsWith(",")){
			jobnos = jobnos.substring(0,jobnos.length()-1);
		}
		return jobnos;
	}
	@Override
	public List<?> getWorkerGroup(HashMap<String, String> params) {
		return attendanceDao.getWorkerGroup(params);
	}
	
	@Override
	public List<?> getprojects(HashMap<String, String> params) {
		return attendanceDao.getprojects(params);
	}
    
	@Autowired
    private DataSourceTransactionManager txManager;
	
	@Override
	public String abnormalAttendance(List<?> l) {
		if(Utils.isNotNull(l)){
			for (int j = 0; j < l.size(); j++) {
				HashMap<String, String> params = (HashMap<String, String>) l.get(j);
				params.put("jobno", params.get("JOBNO"));
				params.put("begTime", params.get("BEGIN_DATE"));
				params.put("endTime", params.get("END_DATE"));
				List<?> l1 = attendanceDao.abnormalAttendance(params);
				for (int i = 0; i < l1.size(); i++) {
					HashMap<String, String> param = (HashMap<String, String>) l1.get(i);
					String recId = param.get("REC_ID");
					String num = param.get("NUM");
					String signTime = param.get("SIGN_TIME");
					String attendanceStatu = param.get("ATTENDANCE_STATUS");
					String clockTime =param.get("CLOCK_TIME");
					if(attendanceStatu.equals("4")){
						clockTime=signTime;
					}
					
					//手动提交事务
//					DataSourceTransactionManager transactionManager = (DataSourceTransactionManager)  AppContext.getInstance().getBean("transactionManager");
					DefaultTransactionDefinition def = new DefaultTransactionDefinition();
					def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务，这样会比较安全些。
					TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
					try {
					AttendanceMethods.AttendanceRecordDataUpdate(recId,num,"1","0","0",clockTime);
					if(num.equals("1") || num.equals("3")){
						//处理首次签到和二次签到异常
						abnormalAttendance1( recId,num,signTime);
					}else if(num.equals("2") || num.equals("4")){
						//处理首次签退和二次签退异常
						abnormalAttendance2(recId,num,signTime);
					}
				
					//最终状态改变（t_attendance_record）
					HashMap<String, String> pa = new HashMap<String, String>();
					pa.put("recId", recId);
					List<?> li =attendanceData(pa);
					String stat="0";
					for (int k = 0; k < li.size(); k++) {
						HashMap<String, String> dt =(HashMap<String, String>) li.get(k);
						String statu= dt.get("ATTENDANCE_STATUS");
						String nums = dt.get("NUM");
						if(!nums.equals(num) && !statu.equals("1")){
							stat="1";
						}
					}
					AttendanceMethods.AttendanceRecordUpdate(recId,stat);
					
					//逻辑代码，可以写上你的逻辑处理代码
					txManager.commit(status);
				  } catch (Exception e) {
					txManager.rollback(status);
				 }
				}
			}
		}
		return "";
	}
	
	public void abnormalAttendance1(String recId,String num,String signTime) {
		HashMap<String, String> params = new HashMap<String, String>();
		if(num.equals("1")){
			num = "2";
		}else{
			num = "4";
		}
		params.put("recId", recId);
		params.put("num", num);
		List<?> l =attendanceData(params);
		if(l.size()>0 && Utils.isNotNull(l.get(0))){
			HashMap<String, String> param = (HashMap<String, String>) l.get(0);
			DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
			int debitType = Integer.parseInt(param.get("DEBIT_TYPE"));
			String lateTmie1 = param.get("LATE_TMIE1");
			String lateTmie2 = param.get("LATE_TMIE2");
			String lateTmie3 = param.get("LATE_TMIE3");
			int timeBase = Integer.parseInt(param.get("TIMEBASE"));
			String signoutTime = param.get("SIGN_TIME");
			String clockTime =param.get("CLOCK_TIME");
			String attendanceStatu= param.get("ATTENDANCE_STATUS");
			String lateTime="";
			String amount=""; 
			if(!attendanceStatu.equals("4") && !attendanceStatu.equals("1") ){
		    	   try
					{
		    		    Date sg = df2.parse(signoutTime);
		    		    Date ct = df2.parse(clockTime);
		    		    if((ct.getTime() - sg.getTime())>=0 ){
		    		    	   attendanceStatu = "1";
						}else{
							   long diff = sg.getTime() - ct.getTime();
							   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
								   attendanceStatu = "1";
							   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
								   DecimalFormat    def   = new DecimalFormat("######0.00");   
								   lateTime = def.format((diff/60000.0))+"";
								   attendanceStatu = "3";
								   amount = def.format((diff/60000.0/timeBase)*debitType)+"";
								   lateTime = lateTime.substring(0, lateTime.indexOf("."));
								   amount = amount.substring(0, amount.indexOf("."));
							   }else{
								   lateTime = AttendanceMethods.TimeDifference(signTime,signoutTime);
						    	   attendanceStatu = "5";
							   }
						}
					}
					catch (Exception e)
					{
					}
		       }
			AttendanceMethods.AttendanceRecordDataUpdate(recId,num,attendanceStatu,lateTime,amount,clockTime);   
		}
	}
	
	
	public void abnormalAttendance2(String recId,String num,String signoutTime) {
		HashMap<String, String> params = new HashMap<String, String>();
		if(num.equals("2")){
			num = "1";
		}else{
			num = "3";
		}
		params.put("recId", recId);
		params.put("num", num);
		List<?> l =attendanceData(params);
		if(l.size()>0 && Utils.isNotNull(l.get(0))){
			HashMap<String, String> param = (HashMap<String, String>) l.get(0);
			DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
			int debitType = Integer.parseInt(param.get("DEBIT_TYPE"));
			String lateTmie1 = param.get("LATE_TMIE1");
			String lateTmie2 = param.get("LATE_TMIE2");
			String lateTmie3 = param.get("LATE_TMIE3");
			int timeBase = Integer.parseInt(param.get("TIMEBASE"));
			String signTime = param.get("SIGN_TIME");
			String clockTime =param.get("CLOCK_TIME");
			String attendanceStatu= param.get("ATTENDANCE_STATUS");
			String lateTime="";
			String amount=""; 
			if(!attendanceStatu.equals("4") && !attendanceStatu.equals("1") ){
		    	   try
					{
		    		    Date sg = df2.parse(signTime);
		    		    Date ct = df2.parse(clockTime);
		    		    if((sg.getTime() - ct.getTime())>=0 ){
		    		    	   attendanceStatu = "1";
						}else{
							   long diff = ct.getTime() - sg.getTime();
							   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
								   attendanceStatu = "1";
							   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
								   DecimalFormat    def   = new DecimalFormat("######0.00");   
								   lateTime = def.format((diff/60000.0))+"";
								   attendanceStatu = "2";
								   amount = def.format((diff/60000.0/timeBase)*debitType)+"";
								   lateTime = lateTime.substring(0, lateTime.indexOf("."));
								   amount = amount.substring(0, amount.indexOf("."));
							   }else{
								   lateTime = AttendanceMethods.TimeDifference(signTime,signoutTime);
						    	   attendanceStatu = "5";
							   }
						}
					}
					catch (Exception e)
					{
					}
		       }
			AttendanceMethods.AttendanceRecordDataUpdate(recId,num,attendanceStatu,lateTime,amount,clockTime);   
		}
		
	}
	
	@Override
	public List<?> attendanceData(HashMap<String, String> params) {
		return attendanceDao.attendanceData(params);
	}

}
